package pers.amos.eshop.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.amos.eshop.dao.RedisDao;
import pers.amos.eshop.mapper.ProductInventoryMapper;
import pers.amos.eshop.model.ProductInventory;
import pers.amos.eshop.service.ProductInventoryService;

/**
 * @author amos wong
 * @create 2020-11-14 4:02 下午
 */
@Service
public class ProductInventoryServiceImpl implements ProductInventoryService {

    @Autowired
    private ProductInventoryMapper productInventoryMapper;

    @Autowired
    private RedisDao redisDao;

    private static final String CACHE_KEY_PREFIX = "product:inventory:";

    @Override
    public void updateProductInventory(ProductInventory productInventory) {
        productInventoryMapper.updateProductInventory(productInventory);
        System.out.println("===========日志===========: 已修改数据库中的库存，商品id=" + productInventory.getProductId() + ", 商品库存数量=" + productInventory.getInventoryCnt());
    }

    @Override
    public void removeProductInventoryCache(ProductInventory productInventory) {
        redisDao.delete(CACHE_KEY_PREFIX + productInventory.getProductId());
        System.out.println("===========日志===========: 已删除redis中的缓存");
    }

    @Override
    public ProductInventory findProductInventoryByProductId(Long productId) {
        return productInventoryMapper.findProductInventoryByProductId(productId);
    }

    @Override
    public void setProductInventoryCache(ProductInventory productInventory) {
        redisDao.set(CACHE_KEY_PREFIX + productInventory.getProductId(),
                String.valueOf(productInventory.getInventoryCnt()));
        System.out.println("===========日志===========: 已更新商品库存的缓存，商品id=" + productInventory.getProductId() + ", 商品库存数量=" + productInventory.getInventoryCnt());
    }

    @Override
    public ProductInventory getProductInventoryCache(Long productId) {
        String result = redisDao.get(CACHE_KEY_PREFIX + productId);
        if (result != null && !"".equals(result)) {
            try {
                Long inventoryCnt = Long.parseLong(result);
                return new ProductInventory(productId, inventoryCnt);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
